package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.nursing.service.IWeChatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: zhengsuyang
 * @Desc:
 * @create: 2025-10-16 15:18
 **/
@Service
public class WeChatServiceImpl implements IWeChatService {
    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.appSecret}")
    private String appSecret;

    private static final String OPENID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private static final String PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    /**
     * 获取openid
     *
     * @return
     */
    @Override
    public String getOpenid(String code) {
        Map<String,Object> hashMap = new HashMap<>();
        hashMap.put("appid",appId);
        hashMap.put("secret",appSecret);
        hashMap.put("js_code",code);
        hashMap.put("grant_type","authorization_code");
        HttpResponse httpResponse = HttpUtil.createRequest(Method.GET, OPENID_URL).form(hashMap).execute();
        if (httpResponse.isOk()){
            String body = httpResponse.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String openid = jsonObject.getStr("openid");
            return openid;
        }
        return null;
    }

    /**
     * 获取phoneNumber
     *
     * @param phoneCode
     */
    @Override
    public String getPhoneNum(String phoneCode) {
        Map<String,Object> hashMap = new HashMap<>();
        hashMap.put("code",phoneCode);
        HttpResponse httpResponse = HttpUtil.createRequest(Method.POST, PHONE_URL + getAccessToken())
                .body(JSONUtil.toJsonStr(hashMap))
                .execute();
        if (httpResponse.isOk()){
            String body = httpResponse.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String phoneNumber = jsonObject.getByPath("phone_info.phoneNumber",String.class);
            return phoneNumber;
        }
        return null;
    }

    private String getAccessToken(){
        Map<String,Object> hashMap = new HashMap<>();
        hashMap.put("grant_type","client_credential");
        hashMap.put("appid",appId);
        hashMap.put("secret",appSecret);
        HttpResponse httpResponse = HttpUtil.createRequest(Method.GET, TOKEN_URL).form(hashMap).execute();
        if (httpResponse.isOk()){
            String body = httpResponse.body();
            JSONObject jsonObject = JSONUtil.parseObj(body);
            String accessToken = jsonObject.getStr("access_token");
            return accessToken;
        }
        return null;
    }
}
